# -*- coding:utf-8 -*-

from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from utils.common_util import CamelCaseUtil, export_list2excel
from module_admin.entity.vo.sys_table_vo import SysTablePageModel
from module_admin.service.sys_table_service import SysTableService
from utils.page_util import PageResponseModel
from module_stock.dao.dc_member_dao import DcMemberDao
from module_stock.entity.do.dc_member_do import DcMember
from module_stock.entity.vo.dc_member_vo import DcMemberPageModel, DcMemberModel


class DcMemberService:
    """
    用户管理模块服务层
    """

    @classmethod
    async def get_dc_member_list(cls, query_db: AsyncSession, query_object: DcMemberPageModel, data_scope_sql: str) -> [list | PageResponseModel]:
        dc_member_list = await DcMemberDao.get_dc_member_list(query_db, query_object, data_scope_sql, is_page=True)
        return dc_member_list

    @classmethod
    async def get_dc_member_by_id(cls, query_db: AsyncSession, dc_member_id: int) -> DcMemberModel:
        dc_member = await  DcMemberDao.get_by_id(query_db, dc_member_id)
        dc_member_model = DcMemberModel(**CamelCaseUtil.transform_result(dc_member))
        return dc_member_model


    @classmethod
    async def add_dc_member(cls, query_db: AsyncSession, query_object: DcMemberModel) -> DcMemberModel:
        dc_member = await DcMemberDao.add_dc_member(query_db, query_object)
        dc_member_model = DcMemberModel(**CamelCaseUtil.transform_result(dc_member))
        return dc_member_model


    @classmethod
    async def update_dc_member(cls, query_db: AsyncSession, query_object: DcMemberModel) -> DcMemberModel:
        dc_member = await DcMemberDao.edit_dc_member(query_db, query_object)
        dc_member_model = DcMemberModel(**CamelCaseUtil.transform_result(dc_member))
        return dc_member_model


    @classmethod
    async def del_dc_member(cls, query_db: AsyncSession, dc_member_ids: List[str]):
        await DcMemberDao.del_dc_member(query_db, dc_member_ids)


    @classmethod
    async def export_dc_member_list(cls, query_db: AsyncSession, query_object: DcMemberPageModel, data_scope_sql) -> bytes:
        dc_member_list = await DcMemberDao.get_dc_member_list(query_db, query_object, data_scope_sql, is_page=False)
        filed_list = await SysTableService.get_sys_table_list(query_db, SysTablePageModel(tableName='dc_member'), is_page=False)
        filtered_filed = sorted(filter(lambda x: x["show"] == '1', filed_list), key=lambda x: x["sequence"])
        new_data = []
        for item in dc_member_list:
            mapping_dict = {}
            for fild in filtered_filed:
                if fild["prop"] in item:
                    mapping_dict[fild["label"]] = item[fild["prop"]]
            new_data.append(mapping_dict)
        binary_data = export_list2excel(new_data)
        return binary_data